package com.mes.cloud.base.feign;

import feign.Feign;
import feign.codec.Encoder;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.cloud.netflix.feign.AnnotatedParameterProcessor;
import org.springframework.cloud.netflix.feign.annotation.PathVariableParameterProcessor;
import org.springframework.cloud.netflix.feign.annotation.RequestHeaderParameterProcessor;
import org.springframework.cloud.netflix.feign.annotation.RequestParamParameterProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.convert.ConversionService;

@Configuration
public class FeignConfiguration {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean //注入默认配置
    public Encoder feignEncoder(ConversionService feignConversionService) {
        return new DefaultEncoder(this.messageConverters, feignConversionService);
    }

    @Bean
    public AnnotatedParameterProcessor pathVariableParameterProcessor() {
        return new PathVariableParameterProcessor();
    }

    @Bean
    public AnnotatedParameterProcessor requestParamParameterProcessor() {
        return new RequestParamParameterProcessor();
    }

    @Bean
    public AnnotatedParameterProcessor requestHeaderParameterProcessor() {
        return new RequestHeaderParameterProcessor();
    }

    @Bean
    public AnnotatedParameterProcessor formParamParameterProcessor() {
        return new FormParamParameterProcessor();
    }

    protected static class TestCase {
        @Bean
        @Scope("prototype")
        @ConditionalOnClass(name = "org.springframework.test.context.junit4.SpringJUnit4ClassRunner")
        public FeignBuilder feignBuilder(BeanFactory beanFactory) {
            return new FeignBuilder(beanFactory, true);
        }
    }

    @Bean
    @Scope("prototype")
    @ConditionalOnMissingClass("org.springframework.test.context.junit4.SpringJUnit4ClassRunner")
    public FeignBuilder feignBuilder(BeanFactory beanFactory) {
        return new FeignBuilder(beanFactory, false);
    }

   // @Bean
   // @Scope("prototype")
    public Feign.Builder feignBuilder() {
        return Feign.builder();
    }

}
